package work.jame.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import work.jame.blog.configuration.security.LoginUser;
import work.jame.blog.framework.exception.BusinessException;
import work.jame.blog.framework.utils.security.SpringSecurityUtils;
import work.jame.blog.pojo.UserArticleLike;
import work.jame.blog.mapper.UserArticleLikeMapper;
import work.jame.blog.service.ArticleService;
import work.jame.blog.service.UserArticleLikeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Jame
 * @since 2023-05-18
 */
@Service
public class UserArticleLikeServiceImpl extends ServiceImpl<UserArticleLikeMapper, UserArticleLike> implements UserArticleLikeService {

    @Autowired
    private ArticleService articleService;

    @Override
    public Long queryArticleLikedNumber(Long articleId) {
        QueryWrapper<UserArticleLike> wrapper = new QueryWrapper<>();
        wrapper.eq("article_id", articleId);
        return this.count(wrapper);
    }

    @Override
    public boolean queryLikedArticle(Long article, Long userId) {
        QueryWrapper<UserArticleLike> wrapper = new QueryWrapper<>();
        wrapper.eq("article_id", article)
                .eq("user_id", userId);
        return this.count(wrapper) == 1;
    }

    @Override
    public boolean likeArticle(Long articleId) {
        Long userId = SpringSecurityUtils.getCurrentLoginUserId();
        if (articleService.queryArticlePublishIsThisUser(articleId, userId)) {
            throw new BusinessException("不能给自己的文章点赞");
        }
        if (this.queryLikedArticle(articleId, userId)) {
            throw new BusinessException("你已经给这篇文章点过赞啦!");
        }
        UserArticleLike userArticleLike = new UserArticleLike();
        userArticleLike.setArticleId(articleId);
        userArticleLike.setUserId(userId);
        return this.save(userArticleLike);
    }

    @Override
    public boolean cancelLikeArticle(Long articleId) {
        Long userId = SpringSecurityUtils.getCurrentLoginUserId();
        if (!this.queryLikedArticle(articleId, userId)) {
            throw new BusinessException("你还没有给这篇文章点过赞哦!");
        }
        QueryWrapper<UserArticleLike> wrapper = new QueryWrapper<>();
        wrapper.eq("article_id", articleId)
                .eq("user_id", userId);
        return this.remove(wrapper);
    }
}
